﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;

namespace Stack_Check
{
    class KeyboardHook : IDisposable
    {
        public const int WM_HOTKEY = 0x0312;

        public event EventHandler HotkeyPressed;

        private Keys key;

        private ModifierKeys modifiers;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private readonly MainWindow window;
        WindowInteropHelper _host;

        private void SetupHotKey(IntPtr handle)
        {
            RegisterHotKey(handle, GetType().GetHashCode(), (int)modifiers, (int)key);
        }

        public KeyboardHook(MainWindow window, Keys key, ModifierKeys modifier)
        {
            this.window = window;
            _host = new WindowInteropHelper(window);
            
            this.key = key;
            this.modifiers = modifier;

            SetupHotKey(_host.Handle);
            ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;
        }

        void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
        {
            if (msg.message == WM_HOTKEY)
            {
                //Handle hot key kere
               
                if (HotkeyPressed != null)
                {
                    Keys key = (Keys)(((int)msg.lParam >> 16) & 0xFFFF);
                    if (key == this.key)
                    {
                        HotkeyPressed(this, EventArgs.Empty);
                        handled = true;
                    }
                }
            }
            
        }

        public void Dispose()
        {
            UnregisterHotKey(_host.Handle, GetType().GetHashCode());
        }
    }
}
